package com.auemall.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.auemall.constant.ApplicationConstant;
import com.auemall.dao.TCategoryBrandsPOMapper;
import com.auemall.dao.TProductbrandPOMapper;
import com.auemall.dao.TProductcategoryPOMapper;
import com.auemall.po.TCategoryBrandsPO;
import com.auemall.po.TCategoryBrandsPOExample;
import com.auemall.po.TProductbrandPO;
import com.auemall.po.TProductcategoryPO;
import com.auemall.po.TProductcategoryPOExample;
import com.auemall.service.ItemCatService;
import com.auemall.utils.EUTreeNode;
import com.auemall.utils.StringUtils;
import com.auemall.vo.BaseRespVO;
import com.auemall.vo.BindCatBrandReqVO;
import com.auemall.vo.CatListVO;
import com.auemall.vo.ItemBrandVO;
import com.auemall.vo.SelectAllCatListRespVO;
import com.auemall.vo.SelectBindBrandRespVO;




@Service
public class ItemCatServiceImpl implements ItemCatService {
    
    private Logger logger = Logger.getLogger(ItemCatServiceImpl.class);

//	@Autowired
//	private TbItemCatMapper itemCatMapper;
	
	@Autowired
    private TProductcategoryPOMapper tProductcategoryPOMapper;
	@Autowired
	private TCategoryBrandsPOMapper tCategoryBrandsPOMapper;
	@Autowired
    private TProductbrandPOMapper productbrandPOMapper;   //品牌表
	
	
	
//	public List<EUTreeNode> getCatList(long parentId) {
//		
//		//创建查询条件
//		TbItemCatExample example = new TbItemCatExample();
//		
//		Criteria criteria = example.createCriteria();
//		
//		criteria.andParentIdEqualTo(parentId);
//		
//		//根据条件查询
//		List<TbItemCat> list = itemCatMapper.selectByExample(example);
//		
//		List<EUTreeNode> resultList = new ArrayList<>();
//		
//		//把列表转换成treeNodelist
//		for (TbItemCat tbItemCat : list) {
//			EUTreeNode node = new EUTreeNode();
//			node.setId(tbItemCat.getId());
//			node.setText(tbItemCat.getName());
//			node.setState(tbItemCat.getIsParent()?"closed":"open");
//			resultList.add(node);
//		}
//		//返回结果
//		return resultList;
//	}
	
	public List<EUTreeNode> getCatList(int parentId) {
        
        //创建查询条件
        TProductcategoryPOExample example =new TProductcategoryPOExample();
        TProductcategoryPOExample.Criteria criteria = example.createCriteria();
        criteria.andParentCategoryIdEqualTo(parentId);
        
        //根据条件查询
        List<TProductcategoryPO> list = tProductcategoryPOMapper.selectByExample(example);
        List<EUTreeNode> resultList = new ArrayList<>();
        
        //把列表转换成treeNodelist
        for (TProductcategoryPO po : list) {
            EUTreeNode node = new EUTreeNode();
            node.setId(po.getId());
            node.setText(po.getName());
            node.setState(po.getParentCategoryId() == ApplicationConstant.IS_PARENT_FLAG ?"closed":"open");
            List<EUTreeNode> children = new ArrayList<EUTreeNode>();
            //创建查询条件
            TProductcategoryPOExample example2 =new TProductcategoryPOExample();
            TProductcategoryPOExample.Criteria criteria2 = example2.createCriteria();
            criteria2.andParentCategoryIdEqualTo(po.getId());
            List<TProductcategoryPO> list2 = tProductcategoryPOMapper.selectByExample(example2);
            for (TProductcategoryPO po2 : list2) {
                EUTreeNode node2 = new EUTreeNode();
                node2.setId(po2.getId());
                node2.setText(po2.getName());
                node2.setState(po2.getParentCategoryId() == ApplicationConstant.IS_PARENT_FLAG ?"closed":"open");
                children.add(node2);
            }
            node.setChildren(children);
            resultList.add(node);
        }
        //返回结果
        return resultList;
    }


    @Override
    public SelectAllCatListRespVO selectAllCatList() throws Exception{
        SelectAllCatListRespVO respVO = new SelectAllCatListRespVO();
        List<CatListVO> catlists = new ArrayList<CatListVO>();
        TProductcategoryPOExample example =new TProductcategoryPOExample();
        TProductcategoryPOExample.Criteria criteria = example.createCriteria();
        criteria.andParentCategoryIdEqualTo(ApplicationConstant.IS_PARENT_FLAG);
        List<TProductcategoryPO> parentMenuList = tProductcategoryPOMapper.selectByExample(example);
        if(parentMenuList != null && parentMenuList.size() > 0){
            for(TProductcategoryPO po : parentMenuList){
                TProductcategoryPOExample example1 =new TProductcategoryPOExample();
                TProductcategoryPOExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andParentCategoryIdEqualTo(po.getId());
                List<TProductcategoryPO> childMenuList = tProductcategoryPOMapper.selectByExample(example1);
                List<CatListVO> childlists = new ArrayList<CatListVO>();
                if(childMenuList != null && childMenuList.size() > 0){
                    for(TProductcategoryPO childPo : childMenuList){
                        CatListVO vo = new CatListVO();
                        if(childPo.getId() != null){
                            vo.setId(childPo.getId().toString());
                        }
                        if(childPo.getParentCategoryId() != null){
                            vo.setParentCategoryId(childPo.getParentCategoryId().toString());
                        }
                        vo.setName(childPo.getName());
                        vo.setSpecification(childPo.getSpecification());
                        vo.setDefaultIcon(childPo.getDefaultIcon());
                        
                        childlists.add(vo);
                    }
                }
                CatListVO vo1 = new CatListVO();
                if(po.getId() != null){
                    vo1.setId(po.getId().toString());
                }
                if(po.getParentCategoryId() != null){
                    vo1.setParentCategoryId(po.getParentCategoryId().toString());
                }
                vo1.setName(po.getName());
                vo1.setSpecification(po.getSpecification());
                vo1.setDefaultIcon(po.getDefaultIcon());
                vo1.setChildren(childlists);
                catlists.add(vo1);
                
            }
        }
        respVO.setCatlists(catlists);
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("查询商品分类菜单成功");
        return respVO;
        
    }


    @Override
    @Transactional
    public BaseRespVO insertCat(CatListVO req) throws Exception {
        BaseRespVO respVO = new BaseRespVO();
        if(req == null){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        TProductcategoryPO record = new TProductcategoryPO();
        BeanUtils.copyProperties(req, record);
        if(StringUtils.isNotBlank(req.getParentCategoryId())){
            record.setParentCategoryId(Integer.parseInt(req.getParentCategoryId()));
        }else{
            record.setParentCategoryId(ApplicationConstant.IS_PARENT_FLAG);
        }
        tProductcategoryPOMapper.insert(record);
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("插入商品分类菜单成功");
        return respVO;
    }


    @Override
    @Transactional
    public BaseRespVO updateCat(CatListVO req) throws Exception {
        BaseRespVO respVO = new BaseRespVO();
        if(req == null){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        if(StringUtils.isBlank(req.getId())){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数[ID]为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        TProductcategoryPO record = new TProductcategoryPO();
        record.setName(req.getName());
        record.setId(Integer.parseInt(req.getId()));
        if(StringUtils.isNotBlank(req.getParentCategoryId())){
            record.setParentCategoryId(Integer.parseInt(req.getParentCategoryId()));
        }else{
            record.setParentCategoryId(ApplicationConstant.IS_PARENT_FLAG);
        }
        tProductcategoryPOMapper.updateByPrimaryKey(record);
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("修改商品分类菜单成功");
        return respVO;
    }


    @Override
    @Transactional
    public BaseRespVO deleteCat(String id) throws Exception {
        BaseRespVO respVO = new BaseRespVO();
        if(!"".equals(id)&& null != id){
            String ids[] = id.split(Pattern.quote(","));
            for (int i = 0; i < ids.length; i++) {
                if(StringUtils.isNotBlank(ids[i])){
                    tProductcategoryPOMapper.deleteByPrimaryKey(Integer.parseInt(ids[i]));
                }
            }
        }
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("删除商品分类菜单成功");
        return respVO;
    }


    @Override
    @Transactional
    public BaseRespVO bindCatBrand(BindCatBrandReqVO req) throws Exception {
        BaseRespVO respVO = new BaseRespVO();
        if(null == req.getCategoryId()){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数[分类菜单ID]为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        if(req.getBrandIds() == null && req.getBrandIds().size() == 0){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数[品牌ID]为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        //1、删除该类别下所有已绑定品牌
        TCategoryBrandsPOExample example = new TCategoryBrandsPOExample();
        TCategoryBrandsPOExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(req.getCategoryId());
        tCategoryBrandsPOMapper.deleteByExample(example);
        //1、循环绑定新选定的品牌
        for(int brandId : req.getBrandIds()){
            TCategoryBrandsPO record = new TCategoryBrandsPO();
            record.setBrandId(brandId);
            record.setCategoryId(req.getCategoryId());
            tCategoryBrandsPOMapper.insert(record);  
        }
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("商品分类与品牌绑定成功");
        return respVO;
    }


    @Override
    public SelectBindBrandRespVO selectBindBrand(String categoryId) throws Exception {
        SelectBindBrandRespVO respVO = new SelectBindBrandRespVO();
        if(StringUtils.isBlank(categoryId)){
            respVO.setResult(ApplicationConstant.RESULT_FALTURE);
            respVO.setMsg("请求参数[categoryId]为空！");
            logger.error(respVO.getMsg());
            return respVO;
        }
        TCategoryBrandsPOExample example = new TCategoryBrandsPOExample();
        TCategoryBrandsPOExample.Criteria criteria = example.createCriteria();
        criteria.andCategoryIdEqualTo(Integer.parseInt(categoryId));
        List<TCategoryBrandsPO> list = tCategoryBrandsPOMapper.selectByExample(example);
        List<ItemBrandVO> brands = new ArrayList<ItemBrandVO>();
        if(list != null && list.size() > 0){
            for(TCategoryBrandsPO po : list){
                ItemBrandVO vo = new ItemBrandVO();
                TProductbrandPO tProductbrandPO = productbrandPOMapper.selectByPrimaryKey(po.getBrandId());
                BeanUtils.copyProperties(tProductbrandPO, vo);
                vo.setId(tProductbrandPO.getId().toString());
                brands.add(vo);
            }
        }
        respVO.setBrands(brands);
        respVO.setResult(ApplicationConstant.RESULT_SUCCESS);
        respVO.setMsg("查询与传入类别关联的品牌成功");
        return respVO;
    }

}
